package com.sse.task;

import com.alibaba.fastjson.JSONObject;
import com.sse.context.SseSessionHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @title: ProgressPushServer
 * @Author xu-xiang
 * @Date: 2024-3-5 14:19:32
 * @description: 进度条测试推送
 */
@Service
public class ProgressPushServer implements ScheduledPushServer {

    private static final Logger logger = LoggerFactory.getLogger(ProgressPushServer.class);

    @Resource
    private Environment environment;

    private int currentProgress;

    @Override
    public Integer getScheduledTime() {
        return 200;
    }

    @Override
    public TimeUnit getTimeUnit() {
        return TimeUnit.MILLISECONDS;
    }

    @Override
    public void run() {

        int maxProgress = 100;
        if (currentProgress < 100) {
            currentProgress = currentProgress + new Random().nextInt(3);

            if (currentProgress > maxProgress) {
                currentProgress = maxProgress;
            }

            // 模拟进度条任务
            JSONObject progress = new JSONObject();
            progress.put("current", currentProgress);
            SseSessionHolder.sendAll(progress.toString());
        }

        // 进度条满,清空到0,用于页面循环展示
        if (currentProgress == maxProgress) {
            currentProgress = 0;
        }
    }
}
